package scparser.factory.ShaderFactory;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.imageio.ImageIO;
import javax.vecmath.Point2d;

import lib.common.ColorOperation;
import lib.common.Constants;
import model.Scene;
import model.Spec;
import model.shader.PhongShader;
import model.shader.Shader;

import scparser.ParserHelper;
import scparser.factory.primitiveFactory.FactoryException;

public class PhongFactory extends ShaderFactory implements ShaderAbstractFactory {
	private Spec spec;
	private Color diff;
	private int samples;
	private String texture;

	public PhongFactory(Scene scene) {
		super.scene = scene;
	}

	@Override
	public Shader create(List<String> block) throws FactoryException {
		String line = null;
		Iterator<String> it = block.iterator();

		try {
			while (it.hasNext()) {
				line = it.next().trim();

				if (line.equals(Constants.S_CLOSE)) {
					break;
				} else if (line.startsWith("name")) {
					super.name = ParserHelper.takeString(line, "name");
				} else if (line.startsWith("diff")) {
					this.diff = ParserHelper.getColor(line);
				} else if(line.startsWith("texture")){
					this.texture = ParserHelper.takeString(line, "texture" );
				} else if (line.startsWith("spec")) {
					this.spec = getSpec(line);
				} else if (line.startsWith("samples")) {
					this.samples = ParserHelper.takeDouble(line, "samples").intValue();
				}
			}
		} catch (IOException e) {
			throw new FactoryException(e.getMessage());
		} catch (FactoryException e) {
			throw new FactoryException(e.getMessage());
		}
		
		// obtenr mapa  de bits a partir de la textura
		
		PhongShader ret;
		if( texture != null){

	 		File file = new File(texture);
	 		BufferedImage textureImage;
	 		try {
				textureImage = ImageIO.read(file);
				Color[] bitmap=ColorOperation.getImageColors(textureImage);
				ret = new PhongShader(super.name, this.diff, this.spec, this.samples, bitmap, textureImage.getWidth(), textureImage.getHeight());
				
	 		}catch (Exception e) {
				ret = new PhongShader(super.name, this.diff, this.spec, this.samples);
			}
		} else {
			ret = new PhongShader(super.name, this.diff, this.spec, this.samples);
		}
		
		if (scene.getShaders().contains(ret)) {
			throw new FactoryException("shader already exists");
		}
		return ret;
	}

}
